package com.zenithmind.user.service.domain.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.security.SecurityUtils;
import com.zenithmind.user.mapper.UserMapper;
import com.zenithmind.user.pojo.domain.User;
import com.zenithmind.user.pojo.query.UserQuery;
import com.zenithmind.user.pojo.vo.UserVO;
import com.zenithmind.user.service.domain.UserQueryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户查询服务实现类
 * 遵循单一职责原则：专门负责用户查询相关功能
 * 遵循开闭原则：通过接口扩展查询功能
 * 遵循依赖倒置原则：依赖UserMapper抽象而非具体实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserQueryServiceImpl implements UserQueryService {

    private final UserMapper userMapper;

    @Override
    @Cacheable(value = "user:id", key = "#id", unless = "#result == null")
    public User getUserById(String id) {
        if (!StringUtils.hasText(id)) {
            return null;
        }
        return userMapper.selectById(id);
    }

    @Override
    @Cacheable(value = "user:username", key = "#username", unless = "#result == null")
    public User getUserByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            return null;
        }
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username)
                   .eq(User::getIsDeleted, 0);
        
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    @Cacheable(value = "user:email", key = "#email", unless = "#result == null")
    public User getUserByEmail(String email) {
        if (!StringUtils.hasText(email)) {
            return null;
        }
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email)
                   .eq(User::getIsDeleted, 0);
        
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public UserVO getUserVOById(String id) {
        User user = getUserById(id);
        if (user == null) {
            return null;
        }
        
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        
        // UserVO中没有password字段，无需设置
        
        return userVO;
    }

    @Override
    public UserVO getCurrentUser() {
        String currentUserId = SecurityUtils.getCurrentUserId();
        if (!StringUtils.hasText(currentUserId)) {
            return null;
        }
        
        return getUserVOById(currentUserId);
    }

    @Override
    public PageResult<UserVO> getUserPage(UserQuery userQuery) {
        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = buildQueryWrapper(userQuery);
        
        // 分页查询
        Page<User> page = new Page<>(userQuery.getCurrent(), userQuery.getSize());
        IPage<User> userPage = userMapper.selectPage(page, queryWrapper);

        // 转换为VO
        List<UserVO> userVOList = userPage.getRecords().stream()
                .map(this::convertToUserVO)
                .collect(Collectors.toList());

        return PageResult.of(userVOList, userPage.getTotal(), (long) userQuery.getCurrent(), (long) userQuery.getSize());
    }

    @Override
    public List<User> getUsersByIds(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return List.of();
        }
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(User::getId, ids)
                   .eq(User::getIsDeleted, 0);
        
        return userMapper.selectList(queryWrapper);
    }

    @Override
    public boolean existsByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            return false;
        }
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username)
                   .eq(User::getIsDeleted, 0);
        
        return userMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public boolean existsByEmail(String email) {
        if (!StringUtils.hasText(email)) {
            return false;
        }
        
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email)
                   .eq(User::getIsDeleted, 0);
        
        return userMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    @Cacheable(value = "user:count", unless = "#result == 0")
    public long countUsers() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getIsDeleted, 0);
        
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    @Cacheable(value = "user:activeCount", unless = "#result == 0")
    public long countActiveUsers() {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getIsDeleted, 0)
                   .eq(User::getStatus, 1); // 1表示启用状态
        
        return userMapper.selectCount(queryWrapper);
    }

    /**
     * 构建查询条件
     * 遵循开闭原则：可以通过扩展UserQuery来添加新的查询条件
     */
    private LambdaQueryWrapper<User> buildQueryWrapper(UserQuery userQuery) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        // 基础条件
        queryWrapper.eq(User::getIsDeleted, 0);

        // 动态条件
        if (StringUtils.hasText(userQuery.getUsername())) {
            queryWrapper.like(User::getUsername, userQuery.getUsername());
        }

        if (StringUtils.hasText(userQuery.getNickname())) {
            queryWrapper.like(User::getNickname, userQuery.getNickname());
        }

        if (StringUtils.hasText(userQuery.getEmail())) {
            queryWrapper.like(User::getEmail, userQuery.getEmail());
        }

        if (StringUtils.hasText(userQuery.getMobile())) {
            queryWrapper.like(User::getMobile, userQuery.getMobile());
        }

        if (userQuery.getStatus() != null) {
            queryWrapper.eq(User::getStatus, userQuery.getStatus());
        }

        // 默认按创建时间倒序排序
        queryWrapper.orderByDesc(User::getCreateTime);
        
        return queryWrapper;
    }

    /**
     * 转换为UserVO
     * 遵循单一职责原则：专门负责实体到VO的转换
     */
    private UserVO convertToUserVO(User user) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        
        // UserVO中已经不包含敏感信息如password
        
        return userVO;
    }
}
